#include<stdio.h>
#include<stdlib.h>

int count = 1;
char Buf[20];
char sExt[5] = ".mid";
char head[4] =
{
    0x4d, 0x54,
    0x68, 0x64
};
char end[5] =
{
    0x00, 0x00, 0xff,
    0x2f, 0x00
};

void handle(FILE * fp)
{
    FILE * out_fp;
    register int i = 1;

    // 判断条件不能调换位置
    while(i < sizeof(head) && fgetc(fp) == head[i])
        i++;

    // 检查是否匹配文件头
    if(i != sizeof(head))
        return;
    // 创建新文件
    sprintf(Buf,"%d%s",count,sExt);
    count++;

    // 处理可能出现的错误
    if(!(out_fp = fopen(Buf,"w")))
    {
        printf("Error!\n");
        exit(0);
    }

    fwrite(head, 1, sizeof(head), out_fp);

    int loop = 0;
    while(loop < sizeof(end))
    {
        i = fgetc(fp);
        if(i == EOF)
            break;
        fputc(i, out_fp);
        //检查是否匹配char end[]
        if(i == end[loop])
            loop++;
        else
            loop = 0;
    }
    //printf("Saved '%s'\n", Buf);
    fclose(out_fp);
    return;
}

int main(int argc,char * argv[])
{
    FILE * in_fp;

    if(argc > 1)
        in_fp = fopen(argv[1], "r");
    else
        in_fp = fopen("a.in", "r");
    if(in_fp == NULL)
    {
        printf("Cannot open the file\n");
        printf("Input enter to exit");
        getchar();
        return -1;
    }

    char buf;
    while(fread(&buf, 1, 1, in_fp) > 0)
        if(buf == head[0])
            handle(in_fp);
    return 0;
}
